package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.ShopListViewAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.ShopEntityClassify;
import com.yksj.healthtalk.entity.ShopListItemEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.views.TagsGridView;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 服务中心商品列表
 * @author Administrator
 *
 */
public class ServerCenterShopList extends BaseFragmentActivity implements OnClickListener,OnRefreshListener<ListView>, OnItemClickListener {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private ShopEntityClassify responEntiry,responEntiry2,responEntiry3,responEntiry1;
	private List<ShopListItemEntity> entities=new ArrayList<ShopListItemEntity>();
	private String flage="2" ;//0-未上架，1-已上架，2-撤销,
	private ShopListViewAdapter adapter;
	private TagsGridView mGridView;
	private String goods_ID="";
	private ExpandGridListAdapter mGridAdapter;
	private List<ShopEntityClassify> mListGrid;
	private ImageView imageRigh;
	private TextView textView1,textView2,textView3;
	public int page=1;
	private String MERCHANT_ID;//商户id
	private String isRecommend="10";
	private int picid;
	private int haveShoppingCar;//购物车是否有商品
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.server_center_shop_list);
		 initView(); 
		MERCHANT_ID=getIntent().getStringExtra("MERCHANT_ID");
		responEntiry=(ShopEntityClassify)getIntent().getSerializableExtra("entity");
		initViewData();
	}

	private void initViewData() {
		page=1;
		isRecommend="10";
		if(responEntiry1==null){
			textView1.setText(responEntiry.getCLASS_NAME());
			responEntiry1=responEntiry;
		}else if(responEntiry2==null){
			textView2.setText(">"+responEntiry.getCLASS_NAME());
			responEntiry2=responEntiry;
			textView2.setVisibility(View.VISIBLE);
		}else if(responEntiry3==null){
			textView3.setText(">"+responEntiry.getCLASS_NAME());
			responEntiry3=responEntiry;
			textView3.setVisibility(View.VISIBLE);
		}else{
			textView3.setText(textView3.getText().toString()+">"+responEntiry.getCLASS_NAME());
			textView3.setVisibility(View.VISIBLE);
		}
		entities.clear();
		initData(page);
	}

	private void initView() {
		initTitle();
		titleTextV.setText("商品列表");
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn2.setVisibility(View.VISIBLE);
		
		titleRightBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		
		titleRightBtn2.setBackgroundResource(R.drawable.server_order);
		titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
		titleLeftBtn.setOnClickListener(this);
		findViewById(R.id.top_line).setVisibility(View.GONE);
		
		adapter = new ShopListViewAdapter(this, entities);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mPullToRefreshListView.setOnRefreshListener(this);
		mListView.setDivider(getResources().getDrawable(R.drawable.list_divider_bg));
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		mListGrid = new ArrayList<ShopEntityClassify>();
		mGridView=(TagsGridView)findViewById(R.id.grid);
		mGridAdapter = new ExpandGridListAdapter(mListGrid,this);
		mGridView.setAdapter(mGridAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				responEntiry=mListGrid.get(position);
				initViewData();
			}
		});
		textView1 = (TextView) findViewById(R.id.text_yaopin1);
		textView1.setOnClickListener(this);
		textView2 = (TextView) findViewById(R.id.text_yaopin2);
		textView2.setOnClickListener(this);
		
		textView3 = (TextView) findViewById(R.id.text_yaopin3);
		textView3.setOnClickListener(this);
		
		imageRigh=(ImageView)findViewById(R.id.viewRigh);
		imageRigh.setOnClickListener(this);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		initData(page);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_right2:
			Intent	intent = new Intent(getApplicationContext(),ServerCenterOrderListActivity.class);
			intent.putExtra("merchant_id", MERCHANT_ID);
			startActivity(intent);
			break;
		case R.id.title_right:
			HttpRestClient.doHttpCartList(MERCHANT_ID,
					new JsonHttpResponseHandler(this){
				@Override
				public void onSuccess(int statusCode, JSONObject response) {
					try {
						if (response.has("info")) { 
							ToastUtil.showToastPanl(response.getString("info"));
						} else if (response.has("money")) {
							Intent intent = new Intent(getApplicationContext(),
									ServerCenterTrolleyActivity.class);
							intent.putExtra("MERCHANT_ID", MERCHANT_ID);
							intent.putExtra("response", response.toString());
							startActivityForResult(intent, 1);
//							{}
						}else {
							Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
							intent.putExtra("MERCHANT_ID", MERCHANT_ID);
							startActivity(intent);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					super.onSuccess(statusCode, response);
				}

				@Override
				public void onSuccess(int statusCode, JSONArray response) {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					startActivity(intent);
					super.onSuccess(statusCode, response);
				}

			});
			break;
		case R.id.title_back:
			finish();
			break;
		case R.id.text_yaopin1:
			page=1;
			textView3.setVisibility(View.GONE);
			textView2.setVisibility(View.GONE);
			entities.clear();
			responEntiry=responEntiry1;
			responEntiry3=null; responEntiry2=null;
			isRecommend="10";
			initData(page);
			break;
		case R.id.text_yaopin2:
			page=1;
			textView3.setVisibility(View.GONE);
			entities.clear();
			responEntiry=responEntiry2;
			responEntiry3=null;
			isRecommend="10";
			initData(page);
			break;
		case R.id.text_yaopin3:
			
			break;
		case R.id.viewRigh:
		if(mGridView.getVisibility()== View.VISIBLE){
			imageRigh.setBackgroundResource(R.drawable.arrows);
			mGridView.setVisibility(View.GONE);}
		else{
				imageRigh.setBackgroundResource(R.drawable.arrows_down_city);
				if(mListGrid.size()>0)
					mGridView.setVisibility(View.VISIBLE);
			}
			break;
		}
		
	}
	

	@Override
	protected void onStart() {
		if (HTalkApplication.haveShoppingCar == 1) {
			titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
		}else {
			titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
		}
		super.onStart();
	}

	private void initData(final int pager) {
		HttpRestClient.doHttpServerShopList(isRecommend,MERCHANT_ID,String.valueOf(pager),responEntiry.getCLASS_ID(),flage,
				new ObjectHttpResponseHandler(this) {
			@Override
			public Object onParseResponse(String cotent) {
				try {
					JSONObject jsonObject=new JSONObject(cotent);
					JSONArray jsonArray = jsonObject.getJSONArray("SUBLIST");
					isRecommend=jsonObject.getString("isRecommend");
					
					if(pager==1){//第一次加载的时候判断购物车就行了
						haveShoppingCar = jsonObject.getInt("HaveShoppingCar");
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if (haveShoppingCar != 0) {
									HTalkApplication.haveShoppingCar = 1;
									titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
								}else {
									HTalkApplication.haveShoppingCar = 0;
									titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
								}
							}
						});
					}

					mListGrid.clear();
					mListGrid.addAll(ShopEntityClassify.parseJsonToInfoRead(jsonArray.toString()));
					
				} catch (JSONException e) {
				}
				
				return ShopListItemEntity.parseToEntity(cotent);
			}
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				mGridAdapter.notifyDataSetChanged();
				mPullToRefreshListView.onRefreshComplete();
				
				if(mListGrid.size()==0){
					imageRigh.setBackgroundResource(R.drawable.arrows);
					mGridView.setVisibility(View.GONE);
				}else{
					imageRigh.setBackgroundResource(R.drawable.arrows_down_city);
					mGridView.setVisibility(View.VISIBLE);
				}
				
				if(!String.valueOf(Long.MAX_VALUE).equals(goods_ID)) {
					if (response != null ) {
						entities.addAll((List<ShopListItemEntity>)response);
					}
					
				}else{
					entities=(List<ShopListItemEntity>)response;
				}
				
				adapter.notifyDataSetChanged();
					
				if(entities.size()>0) {
						goods_ID = entities.get(entities.size()-1).getGOODS_ID();
				}
				page++;
			}
		});
		
	}

	public static class ExpandGridListAdapter extends BaseAdapter{
		final List<ShopEntityClassify> mList;
		final LayoutInflater mInflater;
		
		public ExpandGridListAdapter(List<ShopEntityClassify> list,Context context) {
			this.mList = list;
			this.mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public ShopEntityClassify getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ShopEntityClassify entity = getItem(position);
			TextView textView = null;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.server_shop_list_item,null);
				textView = (TextView)convertView.findViewById(R.id.text_item);
				convertView.setTag(textView);
			}else{
				textView = (TextView)convertView.getTag();
			}
			textView.setText(entity.getCLASS_NAME());
			textView.setTextSize(14);
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent=new Intent(ServerCenterShopList.this,ServerCenterDescription.class);
		ShopListItemEntity entity = entities.get(position-1);
		intent.putExtra("entity", entity);
		intent.putExtra("PICID", picid);
		intent.putExtra("haveShoppingCar", haveShoppingCar);
		startActivity(intent);
		
	}
}
